package com.serbulent.examples.rest;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.serbulent.examples.rest.model.Book;
import com.serbulent.examples.rest.service.IBookService;

@Controller
@RequestMapping("/books")
public class BookStoreController {
	
	List<Book> bookList = null;
	Book book = null;
	
	@Autowired
	IBookService bookService;
	
    @RequestMapping(value = "/index")
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("index");
        return mav;
    }
    
//    @RequestMapping(value = "/index")
//    public String index2() {
//        return "index";
//    }

	
	/**
     * Returns all books.
     *
     * @return all books
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params="callback")
    public ModelAndView getAllBooks(@RequestParam String callback) {
        ModelAndView mav = new ModelAndView();
        bookList = bookService.getAllBooks();
        mav.addObject("Books", bookList);
        return mav;
    }
    
    
	/**
     * Returns all books. If callback parameter does not exits
     *
     * @return all books
     */    
    @RequestMapping(value = "", method = RequestMethod.GET, params="!callback")
    public ModelAndView getAllBooks() {
        ModelAndView mav = new ModelAndView();
        bookList = bookService.getAllBooks();
        mav.addObject("Books", bookList);
        return mav;
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ModelAndView getBookById(HttpServletResponse response,
            @PathVariable("id") int bookId) throws IOException {
    	Assert.notNull(bookId, "Identifier must be provided.");
    	
    	ModelAndView mav = new ModelAndView();
    	book = bookService.getBookById(bookId);
        if (book == null) {
        	book = new Book();
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Book "
                    + bookId + " not found.");
        }
    	
    	mav.addObject("Book", book);
    	return mav;
    }
}
